import json
import inspect


class DataBaseModel:
    table_name = "users"
    connection_string = "sqlite:///database.db"

    def __init__(self, id, name):
        self.id = id
        self.name = name

    @classmethod
    def get_table_info(cls):
        return f"{cls.table_name}-连接地址{cls.connection_string}"

    @staticmethod
    def validate_data(data):
        # 检查传递过来的数据是否是字典
        return isinstance(data, dict)

    def save_data(self, data):
        json_str = json.dumps(data)
        print(f"保存数据{json_str}到{self.table_name}")


# 类级别反射
# print("是否具有类属性table_name=", hasattr(DataBaseModel, "table_name"))
# print("是否具有类属性connection_string=", hasattr(DataBaseModel, "connection_string"))
# print("是否具有类方法get_table_info=", hasattr(DataBaseModel, "get_table_info"))

# print("是否具有类方法save_data=", hasattr(DataBaseModel, "save_data"))

# 动态修改类属性
setattr(DataBaseModel, "table_name", "customers")
print(f"修改后的表名: {DataBaseModel.table_name}")


# 调用类方法
class_method = getattr(DataBaseModel, "get_table_info")
print(class_method())  # 表名: customers, 连接: sqlite:///database.db

# 调用静态方法
static_method = getattr(DataBaseModel, "validate_data")
print(static_method({"key": "value"}))  # True
